接上一篇說到的選擇結構,除了if(單一選擇敘述)還有其他的選擇敘述,下面繼續講
if-else雙向選擇敘述
當if條件運算式不成立,執行else下的程式
import java.util.Scanner;
public class passExam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the score: ");
int score = scanner.nextInt();
if(score >= 60) // greater than 60
System.out.println("pass");
else
System.out.println("Failed");
}
}
else if 的條件敘述
設定多個條件來配合複雜的規則來執行敘述
import java.util.Scanner;
public class ScoreLevel {
public static void main(String[] args)
{
Console console=System.console();
int Score;
System.out.print("Please enter the score: ");
Score=Integer.parseInt(console.readLine());
if(Score<60) { System.out.println("E(Failed)"); }
else if(Score>=60&&Score<=69) { System.out.println("D"); }
else if(Score>=70&&Score<=79) { System.out.println("C"); }
else if(Score>=80&&Score<=89) { System.out.println("B"); }
else if(Score>=90) { System.out.println("A"); }
else { System.out.println("Cannot identify"); }
}
}
多向選擇敘述(switch-case敘述)
switch 是一種多選一的敘述,每一個case跟隨著一個條件,當條件成立執行敘述
switch(變數名稱或運算式) {
case 條件一:
敘述一;
break;
case 條件二:
敘述二;
break;
default:
敘述三;
}
public class SwitchExample {
public static void main(String[] args) {
int dayOfWeek = 3; // Suppose it's Wednesday
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("The day is " + dayName);
}
}